<template>
  <formItem :label="label" @click.native="handleShowPop">
    <div class="form-select">
      <span class="form-text" v-show="selectValue != ''">{{ filterValue(selectValue) }}</span>
      <span class="form-text-placeholder" v-show="selectValue == ''">{{ placeholder }}</span>
      <span class="font_family icon-gengduo form-arrow"></span>
    </div>
    <van-popup position="bottom" get-container="body" v-model="showPop">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPop = false"
      />
    </van-popup>
  </formItem>
</template>
<script>
import formItem from '@/components/form-item'

export default {
  components: {
    formItem
  },
  props: {
    placeholder: {
      type: String,
      default: '请选择',
    },
    label: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => ([])
    },
    optionsKey: {
      type: String,
      default: 'id'
    },
    optionsValue: {
      type: String,
      default: 'value'
    },
    value: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      selectValue: '',
      showPop: false,
      columns: [],
      valueList: [],
    }
  },
  watch: {
    options(newVal) {
      this.valueList = newVal.map(item => item[this.optionsKey])
      this.columns = newVal.map(item => item[this.optionsValue])
    },
    value(newVal) {
      // 赋值判断
      this.selectValue = newVal
    },
    selectValue(newVal) {
      this.$emit('input', newVal)
    }
  },
  methods: {
    handleShowPop() {
      this.showPop = true
    },
    onConfirm(value) {
      const index =  this.columns.indexOf(value)
      this.selectValue = this.valueList[index]
      this.showPop = false
    },
    filterValue(value) {
      // 判断key 和value 是否都是取同一个值
      if (this.optionsKey === this.optionsValue) {
        return value
      } else {
        const index = this.valueList.indexOf(value)
        return this.columns[index]
      }
    },
  },
  mounted() {
    this.selectValue = this.value
    if (this.options) {
      this.valueList = this.options.map(item => item[this.optionsKey])
      this.columns = this.options.map(item => item[this.optionsValue])
    }
  }
}
</script>
<style lang="less" scoped>
.form-select {
  text-align: right;
  line-height: 36px;
}
.form-text-placeholder {
  font-size: 14px;
  color: #011445;
  opacity: 0.6;
}
.form-text {
  font-size: 14px;
  color: #011445;
}
.form-arrow {
  display: inline-block;
  font-weight: normal;
  transform: rotate(90deg);
  margin-left: 10px;
}
</style>